package com.chenyu.util;

import java.io.IOException;
import java.net.URI;

import com.google.common.collect.Lists;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;



public final class UrlUtil {
    private final static String encoding = "utf-8";

    /**
     * 带请求头的post请求
     * 免证书验证的方式
     * @param url
     * @return
     * @throws URISyntaxException
     * @throws IOException
     */
    public static String getURLByPostAndParams(String url, List<NameValuePair> nameValuePairList) throws URISyntaxException,IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //请求参数
//        nameValuePairList.add(new BasicNameValuePair("username", username));
//        nameValuePairList.add(new BasicNameValuePair("password", password));
//        nameValuePairList.add(new BasicNameValuePair("lt", lt));
//        nameValuePairList.add(new BasicNameValuePair("execution", execution));
//        nameValuePairList.add(new BasicNameValuePair("_eventId", _eventId));
        List<Header> headerList = Lists.newArrayList();
        //请求头
        headerList.add(new BasicHeader(HttpHeaders.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"));
        headerList.add(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "gzip, deflate, br"));
        headerList.add(new BasicHeader(HttpHeaders.ACCEPT_LANGUAGE, "zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4,ja;q=0.2,de;q=0.2"));
        headerList.add(new BasicHeader(HttpHeaders.CACHE_CONTROL, "max-age=0"));
        headerList.add(new BasicHeader(HttpHeaders.CONNECTION, "keep-alive"));
        headerList.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"));
        headerList.add(new BasicHeader("DNT", "1"));
        headerList.add(new BasicHeader(HttpHeaders.HOST, "passport.csdn.net"));
        headerList.add(new BasicHeader("Origin", "https://passport.csdn.net"));
        headerList.add(new BasicHeader(HttpHeaders.REFERER, "https://passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn"));
        headerList.add(new BasicHeader("Upgrade-Insecure-Requests", "1"));
        headerList.add(new BasicHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"));

        HttpPost httpPost = new HttpPost(url);
       // httpPost.setHeaders();
       // HFUTRequest hfutRequest = new HFUTRequest();
        String content = EntityUtils.toString(httpClient.execute(httpPost).getEntity());
        System.out.println(content);
        return "";
    }
    /**
     * 无参get请求
     * @param url
     * @return
     * @throws URISyntaxException
     * @throws IOException
     */
    public static String getURLByGet(String url) throws URISyntaxException, IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 定义请求URL和参数，键值对
        URI uri = new URIBuilder(url)
                .build();
        //选择请求方式
        HttpGet httpGet = new HttpGet(uri);
        // 伪装浏览器请求(设置网页头部head)
        httpGet.setHeader(
                "User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");
        //执行请求操作，并拿到结果（同步阻塞）获取response-响应
        CloseableHttpResponse response = httpclient.execute(httpGet);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        String body = "";
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, encoding);
            return body;
        }
        //销毁
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return "";
    }

    /**
     * 无参post请求
     * @param url
     * @return
     * @throws URISyntaxException
     * @throws IOException
     */
    public static String getURLByPost(String url) throws URISyntaxException,IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 定义请求URL和参数，键值对
        URI uri = new URIBuilder(url)
                .build();
        //选择请求方式
        //HttpGet httpGet = new HttpGet(uri);
        HttpPost httpPost = new HttpPost(uri);
        // 伪装浏览器请求(设置网页头部head)
        httpPost.setHeader(
                "User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");
        //执行请求操作，并拿到结果（同步阻塞）获取response-响应
        CloseableHttpResponse response = httpclient.execute(httpPost);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        String body = "";
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, encoding);
            return body;
        }
        //销毁
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return "";
    }

    /**
     * 带参数Post请求
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static CloseableHttpResponse getCloseableHttpResponse(String url , Map params) throws Exception{
        URI uri = null;
        if(params != null && params.size() > 1 )
            uri = new URIBuilder(url).addParameters(CollectionUtil.MapConversionNVP(params)).build();
        else
            uri = new URIBuilder(url).build();
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(uri);
        // 伪装浏览器请求
        httpPost.setHeader(
                "User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");
        return httpclient.execute(httpPost);
    }
    public void tadsa() throws Exception{
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String url = "https://tieba.baidu.com/p/5587497307";
        URI uri = new URIBuilder(url).build();
//        HttpPost httpPost = new HttpPost(uri);
        HttpGet httpGet = new HttpGet(uri);
        // 伪装浏览器请求
        CloseableHttpResponse response = httpclient.execute(httpGet);
        String srtResult = "";
        if(response.getStatusLine().getStatusCode() == 200) {
            srtResult = EntityUtils.toString(response.getEntity());//获得返回的结果
            System.out.println(StringUtil.ConverStringCoding(srtResult,"UTF-8"));

        }
        httpGet.clone();
        response.close();
    }
}
